package com.leon.androidcoursedesign.ui.dialogs;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.Button;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;

import com.leon.androidcoursedesign.R;
import com.leon.androidcoursedesign.ui.activitys.MainActivity;

public class LogoutDialog extends AlertDialog implements View.OnClickListener {
    private Context context;

    public LogoutDialog(@NonNull Context context) {
        super(context);
        this.context = context;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.logout_dialog);

        Window window = getWindow();
        window.setBackgroundDrawableResource(android.R.color.transparent);

        initView();
    }

    private void initView() {
        Button logout_button_cancel = findViewById(R.id.logout_button_cancel);
        logout_button_cancel.setOnClickListener(this);

        Button logout_button_submit = findViewById(R.id.logout_button_submit);
        logout_button_submit.setOnClickListener(this);
    }

    private OnLogoutDialogDismissListener onLogoutDialogDismissListener;

    public interface OnLogoutDialogDismissListener {
        void onDismiss();
    }

    public void setOnLogoutDialogDismissListener(OnLogoutDialogDismissListener onLogoutDialogDismissListener) {
        this.onLogoutDialogDismissListener = onLogoutDialogDismissListener;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.logout_button_cancel:
                dismiss();
                break;
            case R.id.logout_button_submit:
                if (onLogoutDialogDismissListener != null) {
                    onLogoutDialogDismissListener.onDismiss();
                }

                dismiss();
                SharedPreferences preferenceValues = context.getSharedPreferences("preferenceValues", Activity.MODE_PRIVATE);
                SharedPreferences.Editor editor = preferenceValues.edit();
                editor.putBoolean("isAutoLogin", false).apply();

                Intent intent = new Intent(context, MainActivity.class);
                context.startActivity(intent);
                break;
            default:
                break;
        }
    }
}
